import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../util/GenerateUtil.dart';
import '../util/GlobalData.dart';

class UserMessageComponent extends StatelessWidget {
  final String message;
  final String avatarUrl;
  final bool isSelf;

  const UserMessageComponent(
      {super.key,
      required this.message,
      required this.avatarUrl,
      required this.isSelf});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center, // 子组件在主轴（水平）方向上居中
        children: <Widget>[
          Visibility(
              visible: isSelf,
              child: Container(
                padding: EdgeInsets.all(8),
                // width: 50,
                // height: 50,
                // child: Center(child: Text('Left')),
                child: generateMessage(isSelf, avatarUrl, message),
              ).alignLeft()),
          SizedBox(width: 20),
          Visibility(
              visible: !isSelf,
              child: Container(
                padding: EdgeInsets.all(8),
                // width: 50,
                // height: 50,
                child: generateMessage(isSelf, avatarUrl, message),
              ).alignRight()),
        ],
      ),
    );
  }

  Widget generateMessage(
      final bool isSelf, final String avatarUrl, final String message) {
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start;

    List<Widget> widgets = [
      GenerateUtil.generateAvatar(avatarUrl, 50, 50),
      SizedBox(
        width: 4.0,
        height: 4.0,
      ),
      Container(
        padding: EdgeInsets.all(4),
        child: Text(message),
        decoration: BoxDecoration(
          color: Colors.blueAccent,
          border: Border.all(width: 1, color: Colors.blueAccent),
          borderRadius: BorderRadius.circular(8),
        ),
      )
    ];

    if (!isSelf) {
      mainAxisAlignment = MainAxisAlignment.end;
      widgets = widgets.reversed.toList();
    }

    return Container(
      child: Row(
        mainAxisAlignment: mainAxisAlignment,
        children: widgets,
      ),
    );
  }
}

extension AlignmentExtension on Widget {
  Widget alignLeft() {
    return Expanded(
      child: Align(
        alignment: Alignment.centerLeft,
        child: this,
      ),
    );
  }

  Widget alignRight() {
    return Expanded(
      child: Align(
        alignment: Alignment.centerRight,
        child: this,
      ),
    );
  }
}
